package com.example.smssender.contactimport.impl;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import androidx.core.content.ContextCompat;
import com.example.smssender.Contact;
import com.example.smssender.contactimport.ContactImporter;
import com.example.smssender.contactimport.ContactImportManager;
import com.example.smssender.contactimport.ImportResult;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 系统联系人导入器
 */
public class SystemContactImporter implements ContactImporter {
    
    @Override
    public ImportResult importContacts(Context context, Uri source) {
        ImportResult result = new ImportResult();
        
        // 检查权限
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) 
                != PackageManager.PERMISSION_GRANTED) {
            result.setSuccess(false);
            result.addError("需要读取联系人权限");
            return result;
        }
        
        try {
            List<Contact> contacts = readSystemContacts(context);
            
            // 验证和统计
            List<Contact> validContacts = new ArrayList<>();
            for (Contact contact : contacts) {
                if (ContactImportManager.validateContact(contact)) {
                    validContacts.add(contact);
                } else {
                    result.addError("无效数据：" + (contact.getName() != null ? contact.getName() : "未知"));
                }
            }
            
            result.setTotalCount(contacts.size());
            result.setSuccessCount(validContacts.size());
            result.setFailCount(contacts.size() - validContacts.size());
            result.setContacts(validContacts);
            result.setSuccess(true);
            
        } catch (Exception e) {
            result.setSuccess(false);
            result.addError("读取系统联系人失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 读取系统联系人
     */
    private List<Contact> readSystemContacts(Context context) {
        List<Contact> contacts = new ArrayList<>();
        Set<String> processedPhones = new HashSet<>(); // 用于去重（同一联系人可能有多个号码）
        
        Cursor cursor = null;
        try {
            // 查询联系人电话
            cursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                },
                null,
                null,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"
            );
            
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String name = cursor.getString(0);
                    String phone = cursor.getString(1);
                    
                    if (name == null || name.trim().isEmpty()) {
                        continue;
                    }
                    
                    if (phone == null || phone.trim().isEmpty()) {
                        continue;
                    }
                    
                    // 清理手机号
                    String normalizedPhone = ContactImportManager.normalizePhoneNumber(phone);
                    
                    // 跳过非手机号（固定电话等）
                    if (!normalizedPhone.matches("^1[3-9]\\d{9}$")) {
                        continue;
                    }
                    
                    // 去重：同一个手机号只导入一次
                    if (processedPhones.contains(normalizedPhone)) {
                        continue;
                    }
                    
                    processedPhones.add(normalizedPhone);
                    Contact contact = new Contact(name.trim(), normalizedPhone);
                    contacts.add(contact);
                }
            }
            
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        
        return contacts;
    }
    
    @Override
    public String getName() {
        return "系统联系人导入";
    }
    
    @Override
    public String getDescription() {
        return "从手机系统联系人导入";
    }
}

